﻿#region Imports
using System;
using System.Globalization;
using System.Windows.Data;
using CommonUtilities.Attributes;
using CommonUtilities.Extensions;
#endregion Imports

namespace PlayRandom.Converters
{
    public class FriendlyNameConverter : IValueConverter
    {
        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var enumType = System.Convert.ToString(parameter);
            try
            {
                if (enumType == typeof(eRecycleOption).FullName)
                    return GetFriendlyName<eRecycleOption>(value);
                else if (enumType == typeof(eMediaPlayer).FullName)
                    return GetFriendlyName<eMediaPlayer>(value);
                else if (enumType == typeof(eFavouritesOption).FullName)
                    return GetFriendlyName<eFavouritesOption>(value);
                else throw new NotImplementedException("Action not defined for " + enumType);
            }
            catch (NotImplementedException) { throw; }
            catch (Exception) { return System.Convert.ToString(value); }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        #endregion IValueConverter Members

        #region Methods
        private static object GetFriendlyName<TEnum>(object value)
            where TEnum : struct, IComparable, IConvertible, IFormattable
        {
            TEnum med = default(TEnum);
            Enum.TryParse(System.Convert.ToString(value), out med);

            return (med.GetEnumAttribute<TEnum>("FriendlyName") as FriendlyNameAttribute).FriendlyName;
        }
        #endregion Methods
    }
}
